using System;
using System.Collections.Generic;
using System.Text;
using Emlyn.Common.Data.DBUpdater;
using Emlyn.Common.Data.SqlServer.SqlManagers;
using Emlyn.Website.Users;

namespace Emlyn.Website.EmlynORegan.DBUpdateRules
{
    class DUR_0110_MoveToWebsiteUserHierarchy: IDBUpdaterRule
    {
        #region IDBUpdaterRule Members

        public int UpgradeFromVersion()
        {
            return 100;
        }

        public int UpgradeToVersion()
        {
            return 110;
        }

        public void PerformUpgrade()
        {
            string lDropOldObjects1 =
                "ALTER TABLE [dbo].[tblEOUser_Website] DROP CONSTRAINT FK_tblEOUser_Website_tblEOUser ";
            SqlManager.Execute(lDropOldObjects1);

            string lDropOldObjects2 =
                "ALTER TABLE [dbo].[tblEOUser_Website] DROP CONSTRAINT FK_tblEOUser_Website_tblEOWebsite ";
            SqlManager.Execute(lDropOldObjects2);

            string lDropOldObjects3 =
                "drop table [dbo].[tblEOUser_Website]";
            SqlManager.Execute(lDropOldObjects3);

            string lAddWebsiteCodeToUser =
                "ALTER TABLE [dbo].[tblEOUser] ADD " +
                "  [WebsiteCode] [char] (20) COLLATE Latin1_General_CI_AS NOT NULL DEFAULT 'EmlynORegan' ";

            SqlManager.Execute(lAddWebsiteCodeToUser);

            string lUserForeignKeyToWebsite =
                "ALTER TABLE [dbo].[tblEOUser] ADD  " +
                "	CONSTRAINT [FK_tblEOUser_EOWebsite] FOREIGN KEY  " +
                "	( " +
                "		[WebsiteCode] " +
                "	) REFERENCES [dbo].[tblEOWebsite] ( " +
                "		[WebsiteCode] " +
                "	) ON DELETE CASCADE  ON UPDATE CASCADE ";
            SqlManager.Execute(lUserForeignKeyToWebsite);

            User luser = new User();
            luser.UserName = "admin";
            luser.SetPassword("password");
            luser.Email = "admin@need.pwd";
            luser.WebsiteCode = "EmlynORegan";
            luser.ValidationCode = String.Empty;
            luser.AuthLevel = GlobalAuthLevel.GlobalAdmin;

            UserMod luserMod = new UserMod();
            luserMod.Save(luser);
        }

        #endregion
    }
}
